//
//  ChatViewController.m
//  VKChat
//
//  Created by Максим Бризинский on 31.01.11.
//  Copyright 2011 БГУИР. All rights reserved.
//

#import "ChatViewController.h"
#import "Chat.h"


@implementation ChatViewController


-(IBAction) sendMessage:(id)sender {

	if (_uid != 0) {
		
		NSString* uidString = [NSString stringWithFormat:@"%lld",_uid];
		NSLog(@"string %@",uidString);
		NSString* message = [_messageField stringValue];
	
		NSArray* args = [[NSArray alloc] initWithObjects:message, uidString,nil];
	
		[NSThread detachNewThreadSelector:@selector(asyncSendMessage:) toTarget:self withObject:args];
	
		[_messageField setStringValue:@""];
		[_currentChat.messages addObject:message];
		[_messagesTable reloadData];
	}
	
}
-(void)asyncSendMessage:(NSArray*)args {
	//извлекаем параметры для отправки
	NSString* message = [args objectAtIndex:0];
	long uid = [[args objectAtIndex:1] longLongValue];
	
	int err = [_vkApi sendMessage:message toUid:uid];
	if (err == 0) {
		NSLog(@"ME to %lld: %@",uid,message);
	} else {
		NSLog(@"Message ""%@"" to %lld wasn't sent",message, uid);
	}
}

-(void)awakeFromNib {
	_vkApi = [VKApi getInstance];
	_vkApi.receiverMessagesDelegate = self;
	_rosterController.delegate = self;
	[_messagesTable setDataSource:self];
	[_messagesTable setDelegate:self];
}

-(void)didChangeUserUid:(long)uid {
	_uid = uid;
	BOOL found = NO;
	
	for (Chat* chat in _chats) {
		if (chat.uid == _uid) {
			found = YES;
			_currentChat = chat;
			break;
		}
	}
	
	if (!found) {
		Chat* newChat = [[Chat alloc] init];
		newChat.uid = uid;
		newChat.messages = [[NSMutableArray alloc] init];
		[_chats addObject:newChat];
		_currentChat = newChat;
	}
	[_messagesTable reloadData];
}

/* NSTableView Delegate */
-(int)numberOfRowsInTableView:(NSTableView *)tableView {
	int num = [_currentChat.messages count];
	return num;
}

-(id) tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
	return [_currentChat.messages objectAtIndex:row];
}

/*VKApiMessages Delegate */
-(void)didReceiveMessage:(NSString *)message fromUid:(long)uid {
	_uid = uid;
	BOOL found = NO;
	Chat* userChat;
	
	for (Chat* chat in _chats) {
		if (chat.uid == _uid) {
			found = YES;
			userChat = chat;
			[userChat.messages addObject:message];
			break;
		}
	}
	
	if (!found) {
		Chat* newChat = [[Chat alloc] init];
		newChat.uid = uid;
		newChat.messages = [[NSMutableArray alloc] init];
		[newChat.messages addObject:message];
		[_chats addObject:newChat];
		userChat = newChat;
	}
	
	if (userChat == _currentChat)
		[_messagesTable reloadData];	
	
}
@end
